package demo.com.xml;

import android.util.Log;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Created by yangming on 16-11-16.
 */
public class SAXParserHandler extends DefaultHandler {

    private static final String TAG = SAXParserHandler.class.getSimpleName();

    /**
     * 保存节点内容
     */
    private StringBuilder mNodeValue = null;

    /*
     * 标识解析开始
     * @see org.xml.sax.helpers.DefaultHandler#startDocument()
     */
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        mNodeValue = new StringBuilder();
        Log.w(TAG, "----解析开始----");
    }

    /*
     * 标识解析结束
     * @see org.xml.sax.helpers.DefaultHandler#endDocument()
     */
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        Log.e(TAG, "----解析结束----");
    }

    /*
     * 解析XML元素
     * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
    @Override
    public void startElement(String arg0, String arg1, String name,
                             Attributes attributes) throws SAXException {
        super.startElement(arg0, arg1, name, attributes);
        Log.w(TAG, "startElement：" + name);
        int length = attributes.getLength();
        for (int i = 0; i < length; i++) {
            Log.d(TAG, StringUtil.padLeft("属性：" + attributes.getQName(i), 16, ' ') + "    值: " + attributes.getValue(i));
        }
    }

    @Override
    public void endElement(String arg0, String arg1, String name)
            throws SAXException {
        super.endElement(arg0, arg1, name);
        if (0 != mNodeValue.length()) {
            Log.i(TAG, "节点内容：" + mNodeValue.toString().trim());
            mNodeValue.delete(0, mNodeValue.length());
        }
        Log.e(TAG, "endElement：  " + name);
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        String nodeValue = new String(ch, start, length);
        if (!nodeValue.trim().equals("")) {
            mNodeValue.append(new String(ch, start, length));
        }
    }
}
